/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.univcasa.security.auth;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;


/**
 *
 * @author i.makhloufi
 */
public class UserRolesManager {
    static private UserRoles guest;
    public UserRolesManager() {
        try{
            Class.forName("com.mysql.jdbc.Driver");
        }catch (ClassNotFoundException e){
        }
        guest = getUserRoles("guest");
    }
    public UserRoles getUserRolesFromDB(String uid){

        UserRoles result = new UserRoles();
        result.setUid(uid);

        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/comptes_ent","comptesENT" ,"comptesENT");
            PreparedStatement stmt = con.prepareStatement( "SELECT users.role,url,error_page FROM sec_roles_urls urls, sec_users_roles users WHERE urls.role = users.role AND uid like ? ;" );
            stmt.setString(1, uid);
            ResultSet results = stmt.executeQuery();
            int i=0;
            while (results.next() ){
                i++;
                result.setRole( results.getString( 1 )  );
                result.grantResource( results.getString( 2 ) );
                result.setErrorPage(results.getString(3)) ;
            }
        }catch (SQLException ex){
            ex.printStackTrace();
        }finally{
            return result;
        }
    }
    
    public UserRoles getUserRoles(String uid){
        UserRoles result = getUserRolesFromDB(uid);
        if ( "".equals(result.getRole() )){
            return guest;
        }
        else{
            return result;
        }
    }
}
